package com.maxverse.boot.web2image.storage.file;

import com.maxverse.boot.web2image.core.exception.Web2ImageException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Component
public class LocalFileStorage implements FileStorage {
    @Value("${web2image.storage.local.base-path}")
    private String basePath;

    @Override
    public Path getOutputPath(String fileName) {
        String prefix = fileName.substring(0, 2);
        String subdir = fileName.substring(2, 4);
        Path dir = Paths.get(basePath, prefix, subdir);
        try {
            Files.createDirectories(dir);
        } catch (IOException e) {
            throw new Web2ImageException("Failed to create directories", e);
        }
        return dir.resolve(fileName);
    }

    @Override
    public Path save(String taskId, byte[] fileData) {
        try {
            Path dir = Paths.get(basePath, taskId.substring(0, 2), taskId.substring(2, 4));
            Files.createDirectories(dir);
            Path filePath = dir.resolve(taskId + ".jpg");
            Files.write(filePath, fileData);
            return filePath;
        } catch (IOException e) {
            throw new Web2ImageException("Failed to save file for task: " + taskId, e);
        }
    }

    @Override
    public byte[] get(String path) {
        try {
            return Files.readAllBytes(Paths.get(path));
        } catch (IOException e) {
            throw new Web2ImageException("Failed to read file: " + path, e);
        }
    }

    @Override
    public void delete(String path) {
        try {
            Files.deleteIfExists(Paths.get(path));
        } catch (IOException e) {
            throw new Web2ImageException("Failed to delete file: " + path, e);
        }
    }
} 